package com.letoken.platform.repo.sss.validator;

import com.letoken.platform.repo.sss.valid.ValidEthereumAddress;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EthereumAddressValidator implements ConstraintValidator<ValidEthereumAddress, String> {

    @Override
    public void initialize(ValidEthereumAddress constraintAnnotation) {
    }

    @Override
    public boolean isValid(String address, ConstraintValidatorContext context) {
        if (address == null) {
            return false;
        }

        // 转换地址为小写进行统一验证
        String normalizedAddress = address.toLowerCase();

        // 验证长度和前缀
        if (normalizedAddress.length() != 42 || !normalizedAddress.startsWith("0x")) {
            return false;
        }

        // 验证地址部分是否为有效的十六进制数
        String addressPart = normalizedAddress.substring(2);
        return addressPart.matches("[0-9a-f]{40}"); // 40个十六进制字符
    }
}
